<template>
    <el-card>
        <el-button type="primary" :icon="Plus" @click="dialogVisible = true">新增</el-button>
        <!-- 弹框 -->
        <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="是否确认删除?"
            @confirm="confirmEvent"
        >
            <template #reference>
            <el-button :icon="Delete" type="danger">删除</el-button>
            </template>
        </el-popconfirm>
        <!-- 管理列表 -->
        <el-table :data="companionListData"  @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column label="id" prop="id" />
            <el-table-column label="昵称" prop="name" />
            <el-table-column label="头像" prop="avatar">
                <template #="{row}">
                    <el-image style="height: 30px;width: 30px;" :src="row.avatar" fit="cover" />
                </template>
            </el-table-column>
            <el-table-column label="性别" prop="sex">
                <template #="{row}">
                    {{ row.sex===1?'男':'女' }}
                </template>
            </el-table-column>
            <el-table-column label="年龄" prop="age" />
            <el-table-column label="手机号" prop="mobile" />
            <el-table-column label="状态" prop="active">
                <template #="{row}">
                    <el-tag :type="row.active ? 'success':'danger'">{{row.active?'正常':'失效' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="create_time">
                <template #="{row}">
                    {{ formatDate(row.create_time) }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #="{row}">
                    <el-button type="primary" @click="updateCompanion(row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
            <el-pagination
            v-model:current-page="paginationData.pageNum"
            :page-size="paginationData.pageSize"
            :background="background"
            layout="-> ,total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            />
        <!-- 新增和修改 -->
        <el-dialog v-model="dialogVisible" :before-close="beforeClose" :title="!companionForm.id?'新增陪护师':'修改陪护师'"
            width="500">
            <el-form ref="formRef" :model="companionForm" :rules="rules" label-position="left" label-width="auto">
                <el-form-item label="昵称" prop="name">
                    <el-input v-model="companionForm.name" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="头像" prop=" avatar">
                    <el-button v-if="!companionForm.avatar" type="primary" @click="dialogVisible1=true">点击上传</el-button>
                    <el-image v-else :src="companionForm.avatar" style="height: 100px;width: 100px;" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="companionForm.sex" placeholder="请先择性别" size="large" style="width: 240px">
                        <el-option label="男" value="1" />
                        <el-option label="女" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="companionForm.age" :min="age" :max="120" />
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="companionForm.mobile" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="是否生效" prop="active">
                    <el-radio-group v-model="companionForm.active">
                        <el-radio :value="0">失效</el-radio>
                        <el-radio :value="1">生效</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirm(formRef)">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogVisible1" title="选择图片" width="680">
            <div class="image-list">
                <div v-for="(item,index) in fileList" :key="item.name" class="img-box" @click="selectIndex=index">
                    <div v-if="selectIndex === index" class="select">
                        <el-icon color="#fff">
                            <Check />
                        </el-icon>
                    </div>
                    <el-image style="width: 148px;height: 148px;" :src="item.url" />
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible1=false">
                        取消
                    </el-button>
                    <el-button type="primary" @click="confirmImage">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </el-card>
</template>

<script setup>
import {Plus,Delete,Check,InfoFilled} from '@element-plus/icons-vue'
import{ref,reactive,onMounted}from'vue'
import { reqCompanion ,reqPhotoList,reqCompanionList,reqDeleteCompanion} from '../../../api/companion';
import { ElMessage } from 'element-plus';


onMounted(()=>{
    getPhotoList()
    getCompanionList()
})

//陪护师列表
const total=ref(0)
const paginationData=reactive({
    pageNum:1,
    pageSize:10
})
const companionListData=ref([])
const getCompanionList=async()=>{
    const res=await reqCompanionList(paginationData)
    console.log(res);
    
    if(res.data.code===10000){
        companionListData.value=res.data.data.list
        total.value=res.data.data.total
    }

}

//性别显示
const getSexLabel = (value) => {
  switch (value) {
    case 1: return '男';
    case 2: return '女';
    default: return '';
  }
}
//创建时间显示
const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

//分页
const handleCurrentChange=(val)=>{
    paginationData.pageNum=val
    getCompanionList()
}

const handleSizeChange=(val)=>{
    paginationData.pageSize=val
    getCompanionList()
}

//新增或删除陪护师
const dialogVisible=ref(false)
const dialogVisible1=ref(false)
const formRef=ref()
const beforeClose=()=>[
    dialogVisible.value=false,
    formRef.value.resetFields()
    
]
const companionForm=reactive({
    name:'',
    avatar:'',
    sex:'',
    age:28,
    mobile:'',
    active:1

})

const rules=reactive({
    name:[ {required: true,message: '请输入昵称',trigger: 'blur',}],
    avatar:[{required: true,message: '请上传头像'}],
    sex:[{required: true,message: '请选择性别',trigger: 'blur',}],
    mobile:[{required: true,message: '请输入手机号',trigger: 'blur',}]
})

//陪护师头像数据
const fileList=ref([])
const selectIndex=ref(0)
const getPhotoList=async()=>{
    const res=await reqPhotoList()
    if(res.data.code===10000){
        fileList.value=res.data.data
    }
    
}

//确认陪护师头像
const confirmImage=()=>{
  companionForm.avatar=  fileList.value[selectIndex.value].url
  dialogVisible1.value=false

}


//提交陪护师数据
const confirm=async(formEl)=>{
    if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const res= reqCompanion(companionForm)
      if(res.code===10000){
        ElMessage.success('成功')
        dialogVisible.value=false
        beforeClose()
        getCompanionList()
      }else{
        ElMessage.error('失败')
      }
       
    } else {
      console.log('error submit!', fields)
    }
  })
}


//编辑陪护师数据
const updateCompanion=(row)=>{
    dialogVisible.value=true
    companionForm.name=row.name,
    companionForm.avatar=row.avatar,
    companionForm.sex=row.sex,
    companionForm.age=row.age,
    companionForm.mobile=row.mobile
    companionForm.active=row.active
}

//删除陪护师数据
const selecTableData=ref([])
const handleSelectionChange=(val)=>{
    selecTableData.value=val

}

const confirmEvent=async()=>{
    if(!selecTableData.value.length){
       return  ElMessage.warning('请至少选一个项目')
    }
    await reqDeleteCompanion({id:selecTableData.value})
    getCompanionList()
    
    
}

</script>



<style lang="less" scoped>
.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .img-box {
    position: relative;
    .select {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index: 999;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .el-image {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>